package com.hh.vietnameseproject.ui.login

import android.content.Intent
import android.graphics.BitmapFactory
import android.media.Image
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.hh.vietnameseproject.R
import com.hh.vietnameseproject.logic.model.LoginData
import com.hh.vietnameseproject.logic.model.ResponseCode
import com.hh.vietnameseproject.logic.network.AllNetWork
import com.hh.vietnameseproject.ui.MainActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import retrofit2.await

class LoginCodeTabFragment : Fragment() {
    val loginCodeUrl = "http://124.222.92.33/checkCode"
    lateinit var confirmCodeImage:ImageView
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.login_code_fragment, container, false)

        confirmCodeImage = root.findViewById<ImageView>(R.id.loginImage1) //静态验证码换取
        val phone = root.findViewById<EditText>(R.id.loginPhone1)  //手机号
        val logincode = root.findViewById<EditText>(R.id.logincode) //静态验证码
        val loginPhoneCode = root.findViewById<EditText>(R.id.loginPhonecode) //动态验证码
        val loginPhoneCodeBtn = root.findViewById<Button>(R.id.loginPhonecodeBtn) //获取动态验证码
        val loginReturnText = root.findViewById<TextView>(R.id.loginReturnText) //返回数据
        val loginBtn = root.findViewById<Button>(R.id.loginbtn1) //登录按钮


        loginPhoneCodeBtn.setOnClickListener {
            val phoneNum: String? = phone.text.toString().trim()
            val loginCodeText: String? = logincode.text.toString().trim()
            loginReturnText.text = ""


            if (phoneNum == null || phoneNum.equals("")) {
                Toast.makeText(context, "请输入手机号", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (loginCodeText == null || loginCodeText.equals("")) {
                Toast.makeText(context, "请输入静态验证码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }


            loginPhoneCodeBtn.isEnabled = false
            GlobalScope.launch {
                val body = AllNetWork.getPhoneCode(phoneNum, loginCodeText)
                val jsonObject = JSONObject(body.string())
                withContext(Dispatchers.Main) {
                    loginReturnText.text = jsonObject.getString("message")
                }
                if(jsonObject.getInt("code")==1){
                    withContext(Dispatchers.Main){
                        loginPhoneCodeBtn.isEnabled = false
                        loginPhoneCodeBtn.text = "0s后重发"
                    }
                        var i = 61
                        repeat(60) {
                            i--
                            withContext(Dispatchers.Main) {
                                loginPhoneCodeBtn.text = "${i}s后重发"
                            }
                            Thread.sleep(1000)
                        }
                        withContext(Dispatchers.Main) {
                            loginPhoneCodeBtn.isEnabled = true
                            loginPhoneCodeBtn.text = "获取验证码"
                        }

                }else{
                    updateImage()
                    withContext(Dispatchers.Main) {
                        loginPhoneCodeBtn.isEnabled = true
                    }
                }
            }


        }
        loginBtn.setOnClickListener {
            val phoneNum: String? = phone.text.toString().trim()
            val loginPhoneCodeText: String = loginPhoneCode.text.toString().trim()
            if (phoneNum == null || phoneNum.equals("")) {
                Toast.makeText(context, "请输入手机号", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (loginPhoneCodeText == null || loginPhoneCodeText.equals("")) {
                Toast.makeText(context, "请输入手机验证码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            GlobalScope.launch {
                val body = AllNetWork.login(phoneNum, loginPhoneCodeText)
                val jsonObject = JSONObject(body.string())
                val code = jsonObject.getInt("code")
                    withContext(Dispatchers.Main) {
                        if(code==1){
                           //loginReturnText.text = jsonObject.getJSONObject("data").getInt("id").toString()
                            Toast.makeText(context,"${jsonObject.getString("message")}",Toast.LENGTH_SHORT).show()
                            val dataObject = jsonObject.getJSONObject("data")
                            val loginData = LoginData(
                                dataObject.getInt("id"),
                                dataObject.getString("username"),
                                dataObject.getString("phone"),
                                dataObject.getInt("experience"),
                                dataObject.getInt("totaltime"),
                                dataObject.getInt("datecount"),
                                dataObject.getInt("thesaurusId")
                            )
                            val intent = Intent(context, MainActivity::class.java)
                            intent.putExtra("loginData",loginData)
                            startActivity(intent)
                            (context as LoginActivity).finish()
                        }else{
                            loginReturnText.text = jsonObject.getString("message")
                            updateImage()
                        }

                    }
            }


        }

        confirmCodeImage.setOnClickListener {
            updateImage()
        }
        return root
    }

    override fun onResume() {
        super.onResume()
        updateImage()
    }
    fun updateImage(){
        GlobalScope.launch {
            val body = AllNetWork.getCheckCode()
            withContext(Dispatchers.Main) {
                confirmCodeImage.setImageBitmap(BitmapFactory.decodeStream(body.byteStream()))
            }
        }
    }

}